/**
 * created by 小卷毛, 2021-05-21
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.rzico.sbl.viewmodel

import androidx.lifecycle.MutableLiveData
import com.google.android.material.tabs.TabLayout
import com.lzg.extend.BaseResponse
import com.lzg.extend.JsonConvert
import com.lzg.extend.jackson.JacksonConvert
import com.lzg.okrx.RxSingleHelper
import com.lzg.okrx.adapter.FlowableBody
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.model.*
import com.xinnuo.common.extend.conditionIf
import com.xinnuo.common.extend.find
import com.xinnuo.common.extend.optNotEmpty
import com.xinnuo.common.extend.optNotNull
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.helper.longValue
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.applyFlowableSchedulers
import com.xinnuo.common_ui.utils.applySchedulers
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.common_ui.view.BadgeTextView
import org.json.JSONObject

/**
 * 描 述：订单操作相关
 * 作 者：小卷毛  2021-05-21 11:07
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class OrderViewModel : DialogViewModel() {

    val mPayEvent = MutableLiveData<ArrayList<CommonData>>()
    val mTicketEvent = MutableLiveData(0)
    val mMemberEvent = MutableLiveData<ArrayList<MasterData>>()

    val mCountAllEvent = MutableLiveData("0")
    val mCountOneEvent = MutableLiveData("0")
    val mCountTwoEvent = MutableLiveData("0")

    /**
     * 获取订单列表
     */
    fun orderList(
        page: Int,
        state: String,
        roleId: String,
        keyWord: String,
        onSuccess: (ArrayList<Any>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.post<BaseResponse<OrderModel>>(BaseUrl.orderList)
            .isMultipart(true)
            .params(
                getParams(
                    "status" to state,
                    "searchValue" to keyWord,
                    "pageStart" to page * 10,
                    "pageSize" to 10
                )
            )
            .converter(object : JacksonConvert<BaseResponse<OrderModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map {
                ArrayList<Any>().apply {
                    it.data.data.forEachIndexed { index, item ->
                        // 添加头部
                        add(OrderHeader().apply {
                            position = index
                            orderSN = item.sn
                            shippingSn = item.shippingSn.orEmpty()
                            status_hint = item.statusDescr
                            hint = "下单时间: "
                            time = item.createDate.getTimeString()
                        })

                        // 添加商品
                        addItems(
                            item.orderItems.onEach {
                                it.orderSN = item.sn
                                it.shippingSn = item.shippingSn.orEmpty()
                                it.position = index
                                it.hopeDate = item.hopeDate.orEmpty()
                                it.reminderDate = item.reminderDate.orEmpty()
                                it.methodDescr = item.methodDescr.orEmpty()
                                it.fast = item.isFast
                                it.first = item.isFisrst
                            }
                        )

                        // 添加底部
                        add(OrderFooter().apply {
                            position = index
                            orderSN = item.sn
                            shippingSn = item.shippingSn.orEmpty()
                            methodDescr = item.methodDescr.orEmpty()
                            status = item.status.orEmpty()
                            total_num = item.quantity
                            meituanShopName = item.meituanShopName.orEmpty()

                            when {
                                status == "unpaid" -> {
                                    amount = item.amountPayable.orEmpty()
                                    amountHint = "合计: "
                                }

                                methodDescr == "meituan" -> {
                                    amount = item.amountPaid.orEmpty()
                                    amountHint = "商家实收: "
                                }

                                else -> {
                                    amount = item.amountPaid.orEmpty()
                                    amountHint = "实付款: "
                                }
                            }

                            name = item.consignee.orEmpty()
                            phone = item.phone.orEmpty()
                            address = item.address
                            cardMemo = item.cardMemo.orEmpty()
                            memo = item.memo.orEmpty()
                            adminName = item.adminName.orEmpty()
                            adminPhone = item.adminPhone.orEmpty()
                            createDate = item.createDate.getTimeString()
                            hopeDate = item.hopeDate.getTimeString()
                            estimateDate = item.estimateDate.getTimeString()
                            deliveryDate = item.deliveryDate.getTimeString()
                            completeDate = item.completeDate.getTimeString()
                            shippingMethod = item.shippingMethod.orEmpty()
                            isShipping = item.isShipping
                            allowRob = item.allowRob

                            when (status) {
                                "unpaid" -> {
                                    hint_btn1 = "确认订单"
                                    hint_btn2 = "改价"
                                    hint_btn3 = "取消订单"
                                }

                                "unshipped" -> {
                                    hint_btn1 = "发货"
                                    hint_btn2 = conditionIf(roleId == "1", "退款", "")
                                    hint_btn3 = conditionIf(allowRob, "抛单", "")
                                }

                                "shipped" -> {
                                    hint_btn1 = when {
                                        isShipping -> "核销"
                                        roleId == "1" -> "退货退款"
                                        else -> ""
                                    }
                                    hint_btn2 = conditionIf(deliveryDate.isEmpty(), "转派", "")
                                    hint_btn3 = ""
                                }

                                "refunding", "returning" -> {
                                    hint_btn1 = conditionIf(roleId == "1", "确认退款", "")
                                    hint_btn2 = "撤销"
                                    hint_btn3 = ""
                                }

                                "completed" -> {
                                    val completeDate = completeDate.longValue
                                    val currentDate = System.currentTimeMillis()

                                    hint_btn1 = when {
                                        roleId == "1"
                                                && shippingMethod == "pickup"
                                                && (completeDate + 3 * 24 * 60 * 60 * 1000 > currentDate) -> "退款"

                                        else -> ""
                                    }
                                }
                            }
                        })
                    }
                }
            }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 订单详情
     */
    fun orderInfo(orderSN: String) =
        RxSingleHelper.requestString(
            url = BaseUrl.shipInit,
            params = getParams("sn" to orderSN)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 取消订单 BaseUrl.orderCancel
     * 订单退款 BaseUrl.orderRefund
     * 订单退货 BaseUrl.orderReturn
     * 待付款撤销 BaseUrl.orderBack
     * 打印订单 BaseUrl.orderPrint
     */
    fun operateOrder(
        url: String,
        orderSN: String,
        isPost: Boolean = true
    ) =
        RxSingleHelper.requestString(
            method = if (isPost) HttpMethod.POST else HttpMethod.GET,
            url = url,
            params = getParams("sn" to orderSN)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 订单改价
     */
    fun updateOrder(orderSN: String, amount: String) =
        RxSingleHelper.requestString(
            url = BaseUrl.orderUpdate,
            params = getParams(
                "sn" to orderSN,
                "price" to amount
            )
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 付款方式
     */
    fun getPayment() =
        requestCommon(
            isLoading = true,
            requestUrl = BaseUrl.orderWay,
            requestMethod = HttpMethod.GET,
            onSuccess = { mPayEvent.value = it }
        )

    /**
     * 生成付款单
     */
    fun getPaySN(
        orderSN: String,
        amount: String,
        tranSN: String,
        onResult: (String) -> Unit
    ) = request(
        isLoadingBefore = true,
        isLoadingAfter = false,
        requestUrl = BaseUrl.orderPay,
        params = arrayOf(
            "sn" to orderSN,
            "tranSn" to tranSN,
            "amount" to amount
        ),
        onSuccess = {
            val obj = JSONObject(it)
            onResult.invoke(obj.optNotNull("sn"))
        }
    )

    /**
     * 确认订单
     */
    fun confirmOrder(
        paySN: String,
        pluginId: String,
        onResult: () -> Unit
    ) = request(
        isLoadingBefore = false,
        requestUrl = BaseUrl.orderConfirm,
        params = arrayOf(
            "sn" to paySN,
            "paymentPluginId" to pluginId
        ),
        onSuccess = { onResult.invoke() }
    )

    /**
     * 确认发货初始数据
     */
    fun viewOrder(
        orderSN: String,
        type: String = "delivery"
    ) = RxSingleHelper.requestString(
        url = BaseUrl.shipInit,
        params = getParams(
            "sn" to orderSN,
            "type" to type
        )
    )
        .compose(applySchedulers())
        .doOnSubscribe { showLoading() }
        .doFinally { dismissLoading() }

    /**
     * 确认发货
     */
    fun shipOrder(
        orderSN: String,
        method: String,
        shopId: String,
        adminId: String,
        transfer: Boolean,
        price: String,
        memo: String
    ) = RxSingleHelper.requestString(
        url = BaseUrl.orderShip,
        params = getParams(
            "sn" to orderSN,
            "shopId" to shopId,
            "adminId" to adminId,
            "shippingMethod" to method,
            "transfer" to transfer,
            "settlementPrice" to price,
            "memo" to memo,
            "trackingNo" to "",
            "deliveryCorpId" to "",
        )
    )
        .compose(applySchedulers())
        .doOnSubscribe { showLoading() }
        .doFinally { dismissLoading() }

    /**
     * 核销详情
     */
    fun offDetail(orderSN: String) =
        RxSingleHelper.requestString(
            url = BaseUrl.orderOffDet,
            params = getParams("orderSn" to orderSN)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 订单核销
     */
    fun offOrder(shippingSn: String, memo: String) =
        RxSingleHelper.requestString(
            url = BaseUrl.orderOff,
            isMultipart = true,
            params = getParams(
                "sn" to shippingSn,
                "memo" to memo
            )
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 会员水票信息
     */
    fun ticketCount(cardId: String) =
        requestCommon(
            requestUrl = BaseUrl.ticketCount,
            requestMethod = HttpMethod.GET,
            params = arrayOf(
                "cardId" to cardId,
                "subType" to "water"
            ),
            onSuccess = { list ->
                var ticketCount = 0
                list.forEach { ticketCount += it.stock.intValue }

                mTicketEvent.value = ticketCount
            }
        )

    /**
     * 超时订单列表
     */
    fun orderWarnList(
        page: Int,
        state: String,
        roleId: String,
        adminId: String,
        onSuccess: (ArrayList<Any>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<OrderModel>>(BaseUrl.orderWarn)
            .params(
                getParams(
                    "status" to state,
                    "adminId" to adminId,
                    "pageStart" to page * 10,
                    "pageSize" to 10
                )
            )
            .converter(object : JacksonConvert<BaseResponse<OrderModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map {
                ArrayList<Any>().apply {
                    it.data.data.forEachIndexed { index, item ->
                        // 添加头部
                        add(OrderHeader().apply {
                            position = index
                            orderSN = item.sn
                            shippingSn = item.shippingSn.orEmpty()
                            status_hint = item.statusDescr
                            hint = "下单时间: "
                            time = item.createDate.getTimeString()
                        })

                        // 添加商品
                        addItems(
                            item.orderItems.onEach {
                                it.orderSN = item.sn
                                it.shippingSn = item.shippingSn.orEmpty()
                                it.position = index
                                it.hopeDate = item.hopeDate.orEmpty()
                                it.methodDescr = item.methodDescr.orEmpty()
                                it.fast = item.isFast
                                it.first = item.isFisrst
                            }
                        )

                        // 添加底部
                        add(OrderFooter().apply {
                            position = index
                            orderSN = item.sn
                            shippingSn = item.shippingSn.orEmpty()
                            status = item.status.orEmpty()
                            total_num = item.quantity
                            if (status == "unpaid") {
                                amount = item.amountPayable.orEmpty()
                                amountHint = "合计: "
                            } else {
                                amount = item.amountPaid.orEmpty()
                                amountHint = "实付款: "
                            }
                            name = item.consignee.orEmpty()
                            phone = item.phone.orEmpty()
                            address = item.address
                            memo = item.memo.orEmpty()
                            adminName = item.adminName.orEmpty()
                            adminPhone = item.adminPhone.orEmpty()
                            createDate = item.createDate.getTimeString()
                            hopeDate = item.hopeDate.getTimeString()
                            estimateDate = item.estimateDate.orEmpty()
                            deliveryDate = item.deliveryDate.getTimeString()
                            isShipping = item.isShipping
                            allowRob = item.allowRob

                            when (status) {
                                "unpaid" -> {
                                    hint_btn1 = "确认订单"
                                    hint_btn2 = "改价"
                                    hint_btn3 = "取消订单"
                                }

                                "unshipped" -> {
                                    hint_btn1 = "发货"
                                    hint_btn2 = conditionIf(roleId == "1", "退款", "")
                                    hint_btn3 = conditionIf(allowRob, "抛单", "")
                                }

                                "shipped" -> {
                                    hint_btn1 = when {
                                        isShipping -> "核销"
                                        roleId == "1" -> "退货退款"
                                        else -> ""
                                    }
                                    hint_btn2 = conditionIf(deliveryDate.isEmpty(), "转派", "")
                                    hint_btn3 = ""
                                }

                                "refunding", "returning" -> {
                                    hint_btn2 = conditionIf(roleId == "1", "确认退款", "")
                                    hint_btn2 = "撤销"
                                    hint_btn3 = ""
                                }
                            }
                        })
                    }
                }
            }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 获取批量订单列表
     */
    fun batchList(
        page: Int,
        state: String,
        onSuccess: (ArrayList<OrderData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.post<BaseResponse<OrderModel>>(BaseUrl.orderList)
            .params(
                getParams(
                    "status" to state,
                    "pageStart" to page * 10,
                    "pageSize" to 10
                )
            )
            .converter(object : JacksonConvert<BaseResponse<OrderModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 员工列表
     */
    fun memberList() = mDisposables.add(
        OkGo.get<BaseResponse<ResponseModel<MasterData>>>(BaseUrl.mngList)
            .params(
                getParams(
                    "pageStart" to 0,
                    "pageSize" to 500
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<MasterData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }
            .map { it.data.data }
            .subscribeByFinally(
                event = this,
                onSuccess = { mMemberEvent.value = it }
            )
    )

    /**
     * 超时订单数量
     */
    fun warnCount(mAdminId: String = "") {
        request(
            isLoadingBefore = false,
            isLoadingAfter = false,
            isFailed = false,
            requestUrl = BaseUrl.orderWNum,
            requestMethod = HttpMethod.GET,
            params = arrayOf("adminId" to mAdminId),
            onSuccess = {
                val obj = JSONObject(it)

                mCountAllEvent.value = obj.optNotEmpty("all", "0")
                mCountOneEvent.value = obj.optNotEmpty("hope", "0")
                mCountTwoEvent.value = obj.optNotEmpty("over", "0")
            }
        )
    }

    /**
     * 配送员工列表
     */
    fun masterList(
        shopId: String,
        onSuccess: (ArrayList<MasterData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ArrayList<MasterData>>>(BaseUrl.shipList2)
            .params(
                getParams(
                    "shopId" to shopId,
                    "pageStart" to 0,
                    "pageSize" to 500
                )
            )
            .converter(object : JsonConvert<BaseResponse<ArrayList<MasterData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 订单数量
     */
    fun orderCount() =
        RxSingleHelper
            .requestString(url = BaseUrl.orderCount)
            .compose(applySchedulers())
            .doOnSubscribe { }
            .doFinally { }

    /**
     * 更新自定义Tab数量
     */
    fun updateNum(
        unpaid: String,
        unshipped: String,
        shipped: String,
        refunding: String,
        layout: TabLayout
    ) {
        layout.getTabAt(1)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(unpaid)
        }
        layout.getTabAt(2)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(unshipped)
        }
        layout.getTabAt(3)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(shipped)
        }
        layout.getTabAt(4)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(refunding)
        }
    }

    /**
     * 店铺列表
     */
    fun masterShop() =
        OkGo.get<BaseResponse<ResponseModel<MasterData>>>(BaseUrl.mngShop)
            .params(
                getParams(
                    "pageStart" to 0,
                    "pageSize" to 500
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<MasterData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }
            .map { it.data.data }

    /**
     * 待发货且有经纬度订单列表
     */
    fun orderShipList() =
        OkGo.get<BaseResponse<ArrayList<OrderMapData>>>(BaseUrl.orderShipList)
            .converter(object : JacksonConvert<BaseResponse<ArrayList<OrderMapData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }
            .map { it.data }

}